import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Layout from '@/layout'

Vue.use(VueRouter)

/**
 * 路由相关属性说明
 * hidden: 当设置hidden为true时，意思不在sideBars侧边栏中显示
 * mete{
 *  title: xxx,  设置sideBars侧边栏名称
 *  icon: xxx,  设置ideBars侧边栏图标
 *  noCache: true  当设置为true时不缓存该路由页面
 * }
 */

/* common routers */
export const currencyRoutes = [
  {
    path: '/login',
    name: 'Login',
    hidden: true,
    component: () => import('@/views/login')
  },
  {
    path: '/register',
    name: 'Register',
    hidden: true,
    component: () => import('@/views/register')
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error-page'),
    hidden: true
  }
]

/* async routers */
// alwaysShow: 当子组件只有一个，想要展示父组件，则置为true; 否则false
// hideInMenu: 在左侧侧边栏隐藏该路由
export const asyncRoutes = [
  {
    path: '/',
    name: 'Home',
    component: Layout,
    redirect: '/dashbord',
    alwaysShow: false,
    children: [
      {
        path: 'dashbord',
        name: 'Dashbord',
        component: () => import('@/views/dashboard'),
        meta: {
          title: '首页',
          icon: 'el-icon-s-data',
          noCache: false
        }
      }
    ]
  },
  {
    path: '/scene',
    name: 'Scene',
    component: Layout,
    redirect: '/scene/worldsim',
    meta: {
      title: '场景管理',
      icon: 'el-icon-office-building'
    },
    children: [
      {
        path: 'worldsim',
        name: 'WorldSim',
        component: () => import('@/views/scene/worldsim/index.vue'),
        meta: {
          title: 'worldsim',
          noCache: true
        }
      },
      {
        path: 'log2world',
        name: 'log2world',
        component: () => import('@/views/scene/log2world/index.vue'),
        meta: {
          title: 'log2world',
          noCache: true
        }
      },
      {
        path: 'maptest',
        name: 'maptest',
        component: () => import('@/views/scene/maptest/index.vue'),
        meta: {
          title: '城市地图',
          noCache: true
        }
      },
    ]
  },
  {
    path: '/task',
    name: 'TaskCenter',
    component: Layout,
    redirect: '/task/task-run',
    meta: {
      title: '测试中心',
      icon: 'el-icon-set-up',
    },
    children: [
      {
        path: 'task-run',
        name: 'TaskRun',
        component: () => import('@/views/task-center/task-run/index.vue'),
        meta: {
          title: '作业运行',
          noCache: true
        }
      },
      {
        path: 'task-create',
        name: 'TaskCreate',
        component: () => import('@/views/task-center/task-create/index.vue'),
        meta: {
          title: '新建作业',
          noCache: true,
        }
      },
      {
        path: 'task-report/:sessionId',
        name: 'TaskReport',
        component: () => import('@/views/task-center/task-report/index.vue'),
        meta: {
          hideInMenu: true,
          noCache: true,
        }
      },
      {
        path: 'task-detail/:sessionId/:isFinish',
        name: 'TaskDetail',
        component: () => import('@/views/task-center/task-detail/index.vue'),
        meta: {
          hideInMenu: true,
          noCache: true,
        }
      },
      {
        path: 'task-log/:taskId',
        name: 'TaskLog',
        component: () => import('@/views/task-center/task-log/index.vue'),
        meta: {
          hideInMenu: true,
          noCache: true,
        }
      },
    ]
  },

  {
    path: '/metric',
    name: 'Metric',
    component: Layout,
    redirect: '/metric/metric-library',
    alwaysShow: true,
    meta: {
      title: '测试指标',
      icon: 'el-icon-pie-chart'
    },
    children: [
      {
        path: 'metric-library',
        name: 'MetricLibrary',
        component: () => import('@/views/metric/metric-library/index.vue'),
        meta: {
          title: '指标库',
          noCache: true
        }
      }
    ]
  },
  {
    path: '/source',
    name: 'Source',
    component: Layout,
    redirect: '/source/pnc',
    alwaysShow: true,
    meta: {
      title: '资源管理',
      icon: 'el-icon-coin'
    },
    children: [
      {
        path: 'pnc',
        name: 'Pnc',
        component: () => import('@/views/source/pnc'),
        meta: {
          title: '算法版本',
          noCache: true
        }
      },
      {
        path: 'node',
        name: 'Node',
        component: () => import('@/views/source/node'),
        meta: {
          title: '节点管理',
          noCache: true
        }
      }
    ]
  },
  {
    path: '*',
    name: '*404',
    redirect: '/404',
    hidden: true
  }
]

const creatRouter = () => {
  return new VueRouter({
    routes: currencyRoutes,
    scrollBehavior() {
      return {
        x: 0,
        y: 0
      }
    }
  })
}

const router = creatRouter()

// 解决addRoute不能删除动态路由问题
export function resetRouter() {
  const reset = creatRouter()
  router.matcher = reset.matcher
}

// 路由钩子 处理逻辑
router.beforeEach(async (to, from, next) => {
  const noRequireAuth = ['/register', '/login']
  // 需要用户认证的页面
  if (!noRequireAuth.includes(to.path)) {
    if (!getToken()) {
      // 用户未登录，需要重新登录
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将当前访问的页面路径作为参数传递给登录页面 【在request 页面也实现】
      });
    } else {
      // 用户已登录
      let hasRoles = store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          const roles = await store.dispatch('user/getUserRoles')
          const addRoutes = await store.dispatch(
            'permission/getAsyncRoutes',
            roles
          )
          router.addRoutes(addRoutes)
          next({
            ...to,
            replace: true
          })
        } catch (err) {
          throw err
        }
      }
    }
  } else {
    // 不需要用户认证的页面
    next();
  }
});
// vue-router 3.x 必需监听 错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
